<?php

namespace App\Http\Middleware;

use App\Models\Site;
use App\Services\ConfigService;
use Closure;
use Illuminate\Support\Facades\Log;

class FrontMiddleware
{

    //定义中间件，获取url地址，并匹配对应站点的域名，然后存入session，site和module
    public function handle($request, Closure $next)
    {

        $this->init();
        config(['site' => site()['config']]);

        return $next($request);
    }

    protected function init()
    {

        $info = parse_url(request()->url());
        $site = Site::where('domain', 'regexp', 'https?://' . $info['host'])->first();
        if ($site) {
            site($site);
            //纠错，防止没有默认模块时导致404
            if ($site->module) {
                module($site->module->name);
                app(ConfigService::class)->loadCurrentModuleConfig();
            }
        }
    }
}
